package com.xaioran.security.config;

import com.xaioran.security.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService  implements UserDetailsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    // 总目标：根据表单提交的用户名字，去数据库中查询出对应的User对象，并装配角色，权限等信息
    public UserDetails loadUserByUsername(/*表单提交用户名*/String username) throws UsernameNotFoundException {

        // 1 从数据库中去查询Admin对象
            String sql="select id,loginacct,userpswd,username,email from t_admin where loginacct=?";
            List<Admin> adminList=jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Admin.class),username);
            Admin admin=adminList.get(0);
            String userpswd=admin.getUserpswd();

        // 2 给admin设置角色权限信息 ，必须设置就算为空也得设置一个
            List<GrantedAuthority> authorities=new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); // 设置角色 "ROLE_"  必须以这个开头
            authorities.add(new SimpleGrantedAuthority("ROLE_"+"学徒"));
            authorities.add(new SimpleGrantedAuthority("UPDATE")); // 设置权限，不需要特殊的开头

        // 3 把admin对象 和 authorities封装到一个UserDetails中
        return new User(username,userpswd,authorities);
    }
}
